# koroFileHeader at Yungoal acer
# Create: 2023-10-19 10:06:49
# LastEdit: 2023-10-25 17:33:12
"""列出有权限的资源组
https://next.api.aliyun.com/api/ResourceManager/2020-03-31/ListResourceGroups
"""
__author__ = '749B'
# pylint: disable=import-error, wrong-import-position

if __name__ == '__main__':
    # 导入路径
    from pathlib import Path
    BASE_DIR = Path(__file__).resolve().parent.parent
    import sys
    sys.path.append(str(BASE_DIR))
    # Django 初始化
    import django
    from django.conf import settings
    from ygcmp import settings as my_settings
    settings.configure(**{ k: v for k, v in vars(my_settings).items() if k.isupper() })
    django.setup()


import logging

# pylint: disable-next=ungrouped-imports
from django.utils import dateparse, timezone

from apps.resourcemanager import models
from utils.alibabacloud.resourcemanager import list_resource_groups

from tasks.thread_task import BaseTask


class SyncResourceGroups(BaseTask):

    def __init__(self, account: models.Account):
        self.account = account
        self.user = account.user_set.filter(status=True).first()
        self._client = None
        super().__init__(task_name=self.account.name)

        self.logger = logging.getLogger(f"tasks.{self.__class__.__name__}")
        self.logger.success = lambda msg, *args, **kwargs: self.logger.log(25, msg, *args, **kwargs)

    @BaseTask.set_task_info
    def run(self):
        self.logger.info('同步资源组任务开始: %s', self.task_key[1])
        rg_name_list = []
        for resource_group in list_resource_groups(self.user.rm_client):
            create_date = dateparse.parse_datetime(resource_group['CreateDate'])
            rg_obj, _ = models.ResourceGroup.objects.update_or_create(
                name=resource_group['Name'],
                acc=self.account,
                defaults={
                    'rid': resource_group['Id'],
                    'display_name': resource_group['DisplayName'],
                    'status': resource_group['Status'],
                    'account_id': resource_group['AccountId'],
                    'create_date': create_date,
                    'acc': self.account,
                    }
                )
            for tag in resource_group['Tags']['Tag']:
                tag_key, tag_value = tag['TagKey'], tag['TagValue']
                key_obj, _ = models.TagKey.objects.get_or_create(
                    key=tag_key, account=self.account)
                models.TagValueRg.objects.update_or_create(
                    tag_key=key_obj, resource_group=rg_obj,
                    defaults={'value': tag_value}
                    )
            # 批量删除多对多关联
            # https://docs.djangoproject.com/zh-hans/4.2/topics/db/optimization/#remove-in-bulk
            (
                models.TagValueRg.objects
                .filter(resource_group=rg_obj)
                .exclude(tag_key__key__in=[ t['TagKey'] for t in resource_group['Tags']['Tag'] ])
                .delete()
                )
            rg_name_list.append(resource_group['Name'])
        # 没有更新到的记录，添加dtime字段值。一次修改多个对象
        (
            models.ResourceGroup.objects
            .filter(acc=self.account)
            .exclude(name__in=rg_name_list)
            .update(dtime=timezone.now())
            )
        self.logger.info('同步资源组任务完成: %s', self.task_key[1])


if __name__ == '__main__':
    for acc in models.Account.objects.all():
        task = SyncResourceGroups(acc)
        started = task.start()
        if started:
            print('同步资源组开始', task.task_key[1])
        else:
            print('任务未开始', task.task_start_msg)
        # 可以去掉下面的语句，多个账号可以同时同步数据，就是任务日志会比较乱
        # pylint: disable-next=expression-not-assigned
        task.join() is None and print('同步订阅结束', task.task_key[1])
    